import $service from '../../../../service'
const app = getApp();
let isOnce = true
let isFinish = false
Component({
  properties: {
    bottomHeight: { // 聊天室底部操作栏高度
      value: '0',
      type: String
    },
    logId: { // 问诊id
      value: '',
      type: String
    },
    friendIM: { // 对方ImId
      value: '',
      type: String
    },
    myIM: { // 自己ImId
      value: '',
      type: String
    },
    userType: { // 用户类型 1 用户 2 医生
      value: '1',
      type: String
    },
    doctorName: { //医生名称
      value: '',
      type: String
    },
    userName: { // 用户名称
      value: '',
      type: String
    },
    logType: { // 问诊类型
      value: '1',
      type: String
    },
    userIDImg: { // 自己头像
      value: '',
      type: String
    },
    selToIDImg: { // 对方头像
      value: '',
      type: String
    },
    isWithdrawShow: {
      value: false,
      type: Boolean
    },
    toView: {
      value: '',
      type: String
    },
    isCompleted: { // 是否已完成医助信息
      value: '',
      type: String
    },
    chatType: { //是否已经结束问诊
      value: '',
      type: String
    }
  },

  data: {
    msgList: [], // 消息数组
    scrollTop: 0, // 滚动高度
    addTop: false,
    triggered: false,
  },
  lifetimes: {
    ready() {
      isOnce = true
      this.getChatRecordList();
    },
  },
  methods: {
    myMessage(res) {
      this.data.msgList.push(res)
      this.setData({
        msgList: this.data.msgList
      })
      this.bottom()
    },
    isReadMessage() {
      console.log(this.data.msgList);
      if (this.data.msgList.length==0) {} 
      else {
        this.data.msgList[this.data.msgList.length - 1].isRead = 1
        this.setData({
          msgList: this.data.msgList
        })
      }
    },
    tagetMessage(res) {
      if (res.msgType == 4) { // 消息撤回信息
        this.data.msgList.forEach((item, index) => {
          if (item.id == res.id) {
            this.data.msgList.splice(index, 1)
          }
        })
      } 
      this.data.msgList.push(res)
      console.log(this.data.msgList)
      this.setData({
        msgList: this.data.msgList
      })
      this.bottom()
    },
    withdrawShow(e) {
      let {
        info
      } = e.currentTarget.dataset
      let time = new Date().getTime() - $service.dataFormat(info.msgDate);
      let setTime = 2 * 60 * 1000
      if (time < setTime && info.msgUserName != '系统') { // 判断是发送两分钟
        let height = wx.getSystemInfoSync().windowHeight * 3 / 5
        let {
          clientY
        } = e.changedTouches[0] //获取元素距离顶部的高度
        let bel = height <= clientY
        this.setData({
          addTop: bel,
          isWithdrawShow: true,
          withdrawId: info.id
        })
      } else {
        $service.showToast('该消息不可撤回')
      }
    },
    // 隐藏撤回弹窗
    closeWithdraw() {
      this.setData({
        isWithdrawShow: false
      })
    },
    // 点击撤回
    withdraw(e) {
      this.setData({
        isWithdrawShow: false
      })
      let {
        index,
        info
      } = e.currentTarget.dataset
      let trueName = this.data.userName
      if (this.data.userType === '2') {
        trueName += '医生'
      }
      let msgData = {
        "id": info.id, //消息id
        "msgText": `对方撤回了一条信息`, // 信息体
        "friendId": this.data.friendIM, // 接收方的用户imID
        "msgType": 4, // 消息类型；0文字消息、1固定表情 3 图片url 4 撤回
        "inquiryLogId": this.data.logId,
        "msgDate": $service.getDate(), // 发送时间
        "msgUserName": this.properties.userName,
        "packageType": 3 // 信息包类型
      }
      app.webSocket.sendWebSocketMsg({
        data: msgData,
        success: () => { // 发送撤回消息成功之后更改对于id消息的内容
          this.data.msgList[index].msgDate = msgData.msgDate;
          this.data.msgList[index].userId = this.data.myIM;
          this.data.msgList[index].msgText = '你撤回了一条消息';
          this.data.msgList[index].packageType = 4;
          this.data.msgList[index].msgType = 4;
          this.setData({
            msgList: this.data.msgList
          })
        },
        fail: () => {
          $service.showToast('撤回失败')
        }
      })
    },
    // 获取历史聊天记录
    getChatRecordList(e) {
      if (e === 'reset') {
        this.data.msgList = []
        isOnce = true
        console.log(1);
      }
      let params = {
        "friendId": this.data.friendIM, // 对方imID
        // "id": this.data.msgList.length !== 0 ?  this.data.msgList[0].id : '',
        "id": this.data.msgList.length !== 0 ? this.data.msgList[0].id : '',
        "userId": this.data.myIM // 自己imID
      }
      app.http.getChatRecordList(params).then(res => {
        let list = res.data;
        list.forEach(item => {
          if (item.friendId == item.userId) {
            item.packageType = 4
            //判断是当前的问诊记录
            console.log(this.properties.logId);
            if (this.properties.logId == item.inquiryLogId) {
              item.isThisLog = 1
            } else {
              item.isThisLog = 0
            }
            console.log(item)
          } else {
            item.packageType = item.userId == this.data.myIM ? 3 : 4
          }
        })
        if (isOnce) { // 当第一次进入聊天室时将消息置底
          isOnce = false
          this.setData({
            msgList: list
          })
          this.bottom()
        } else { // 当触顶加载历史记录时把视图位置设置到第一次最后一条信息的位置
          this.setData({
            msgList: list.concat(this.data.msgList)
          })
          this.setData({
            toView: 'v' + params.id
          })
        }
      }).catch(err => {
        $service.showToast(err.msg)
      })
    },
    upper() {
      this.getChatRecordList()
    },
    bottom() {
      this.setData({
        toView: 'flag'
      })
    },
    outbtn() {
      this.setData({
        isWithdrawShow: false
      })
      this.triggerEvent('outbtn')
    },
    previewImg(e) {
      let {
        src
      } = e.target.dataset
      
      wx.previewImage({
        current: src, // 当前显示图片的http链接
        urls: [src.replace(/https/, 'http')] // 需要预览的图片http链接列表
      })
    },
    finished(e) {
      if (this.properties.isCompleted == 1) return
      else {
        if (e.currentTarget.dataset.isthislog == 0) {
          return
        }
        let msgData = {
          "logId": this.data.logId,
          "userIm": this.data.myIM,
          "doctorIm": this.data.friendIM,
          "packageType": 30
        }
        app.webSocket.sendWebSocketMsg({
          data: msgData,
          success: () => {
            let params = {
              packageType: 3,
              msgType: "6",
              friendId: this.properties.myIM,
              msgText: '已经收到您的信息啦~若等候时长过长，您可选择离线等待本次问诊哦！',
              inquiryLogId: this.properties.logId,
              msgUserName: this.properties.doctorName,
              msgDate: $service.getDate()
            }
            app.webSocket.sendWebSocketMsg({
              data: params
            })
            this.triggerEvent('finished')
          },
          fail: () => {
            $service.showToast('操作失败')
          }
        })
      }
    },
    goDetail(e) {
      let {
        id
      } = e.currentTarget.dataset
      $service.openPage('/pages/user_side/my_doctor/inventory/inventory?id=' + id)
    }
  }
})